import React, { FC, useEffect, useState, useRef, useMemo } from "react";
import styles from "./common.module.scss";
import QuestionCard from "../../components/QuestionCard";
import { useDebounceFn, useRequest, useTitle } from "ahooks";
import { Empty, Spin, Typography } from "antd";
import ListSearch from "../../components/ListSearch";
import { useSearchParams } from "react-router-dom";
import { getQuestionListService } from "../../services/question";
import { LIST_PAGE_SIZE, LIST_SEARCH_PARAM_KEY } from "../../constant";

const { Title } = Typography;
const List: FC = () => {
  useTitle("乌鸦问卷-我的问卷");
  const [started, setStarted] = useState(false); //是否已经开始加载 (防抖,有延迟时间)
  const [page, setPage] = useState(1);
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);
  const haveMoreData = total > list.length; //有没有更多的数据
  const [searchParams] = useSearchParams();

  const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || "";
  useEffect(() => {
    // keyword变化，重置信息
    setStarted(false);
    setList([]);
    setPage(1);
    setTotal(0);
  }, [keyword]);

  const { run: load, loading } = useRequest(
    async () => {
      const data = await getQuestionListService({
        page,
        pageSize: LIST_PAGE_SIZE,
        keyword,
      });
      return data;
    },
    {
      manual: true,
      onSuccess(result) {
        const { list: l = [], total = 0 } = result;
        setList(list.concat(l)); //累计
        setTotal(total);
        setPage(page + 1);
      },
    }
  );

  // ahooks 防抖
  const containerRef = useRef<HTMLDivElement>(null);
  const { run: tryLoadMore } = useDebounceFn(
    () => {
      // 触发加载
      // 判断dom 元素的高度是否小于body的，如果是则代表下滑加载更多dom已经出现 在视口
      const elem = containerRef.current;
      if (elem == null) return;
      const domRect = elem.getBoundingClientRect();
      if (domRect == null) return;
      const { bottom } = domRect;
      if (bottom <= document.body.clientHeight) {
        // 加载数据
        load();
      }
    },
    {
      wait: 1000,
    }
  );
  //当页面加载或者url参数变化时，触发加载
  useEffect(() => {
    // 第一次加载
    tryLoadMore();
  }, [searchParams]);

  // 监听页面滚动，尝试触发加载
  useEffect(() => {
    if (haveMoreData) {
      window.addEventListener("scroll", tryLoadMore);
      return () => {
        window.removeEventListener("scroll", tryLoadMore); //组件卸载，解绑事件
      };
    }
  }, [searchParams, haveMoreData]);

  //useMemo 刷新缓存函数
  const LoadMoreContentElem = useMemo(() => {
    if (!started || loading) return <Spin></Spin>;
    if (total === 0) return <Empty description="暂无更多数据"></Empty>;
    if (!haveMoreData) return <span>没有更多了....</span>;
    return <span>开始加载下一页</span>;
  }, [started, loading, haveMoreData]);

  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}> 我的问卷</Title>
        </div>
        <div className={styles.right}>
          <ListSearch></ListSearch>
        </div>
      </div>
      <div className={styles.content}>
        {/* 问卷列表 */}
        {list.length > 0 &&
          list.map((q: any) => {
            const { _id } = q;
            return <QuestionCard key={_id} {...q}></QuestionCard>;
          })}
      </div>
      <div className={styles.footer}>
        <div ref={containerRef}>{LoadMoreContentElem}</div>
      </div>
    </>
  );
};

export default List;
